#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>

#include "../include/unicom.h"
#include "../include/ipc.h"
#include "../include/display_env.h"

#define STORAGE_NO 1
#define WEB_ENV_ST1_N 32

/*
 *仓库1环境的网页显示，共享内存实现，数据流向:main从串口获取Zigbee数据，写到共享内存
 *环境网页显示共享内存的信息
 **/
int init_shm(struct ipc_info *p_ipc_info)
{
	if ((p_ipc_info->skey = ftok("/app", 'i')) < 0)
	{
		perror("init_ipc: ftok");
		exit(-1);
	}

	if ((p_ipc_info->semid = semget(p_ipc_info->skey, 1, IPC_EXCL)) < 0)
	{
		fprintf(stderr, "semphore %#x was not exist !\n", p_ipc_info->skey);
		if ((p_ipc_info->semid = semget(p_ipc_info->skey, 1, 0666 | IPC_CREAT)) < 0)
		{
			perror("init_shm, semphore create");
			exit(-1);
		}
		fprintf(stderr, "semphore %#x was create success !\n", p_ipc_info->skey);
	}

	init_sem(p_ipc_info->semid, 0, 1);

	if ((p_ipc_info->shmid = shmget(p_ipc_info->skey, WEB_ENV_ST1_N, IPC_EXCL)) < 0)
	{
		fprintf(stderr, "share memery %#x was not exist !\n", p_ipc_info->skey);
		if ((p_ipc_info->shmid = shmget(p_ipc_info->skey, WEB_ENV_ST1_N, 0666 | IPC_CREAT)) == -1)
		{
			perror("init_shm, share memery create");
			exit(-1);
		}
		fprintf(stderr, "share memery %#x was create success !\n", p_ipc_info->skey);
	}
	return 0;
}

void show_env2web(struct ipc_info *p_ipc_info, struct sendEnv *house_env)
{
	struct shm_addr *shm_buf = NULL;

	if ((shm_buf = (struct shm_addr *)shmat(p_ipc_info->shmid, NULL, 0)) == (void *)-1)
	{
		perror("shmat");
		return;
	}

	sem_p(p_ipc_info->semid, 0);

	shm_buf->rt_status.storage_no[STORAGE_NO].storage_status = 1;
	shm_buf->rt_status.storage_no[STORAGE_NO].led_status = 1;
	shm_buf->rt_status.storage_no[STORAGE_NO].buzzer_status = 1;
	shm_buf->rt_status.storage_no[STORAGE_NO].fan_status = 1;
	shm_buf->rt_status.storage_no[STORAGE_NO].seg_status = 1;
	shm_buf->rt_status.storage_no[STORAGE_NO].x = house_env->x;
	shm_buf->rt_status.storage_no[STORAGE_NO].y = house_env->y;
	shm_buf->rt_status.storage_no[STORAGE_NO].z = house_env->z;
	shm_buf->rt_status.storage_no[STORAGE_NO].temperature = house_env->temp[0];
	shm_buf->rt_status.storage_no[STORAGE_NO].temperatureMIN = 18;
	shm_buf->rt_status.storage_no[STORAGE_NO].temperatureMAX = 80;
	shm_buf->rt_status.storage_no[STORAGE_NO].humidity = house_env->hum[0];
	shm_buf->rt_status.storage_no[STORAGE_NO].humidityMIN = 10;
	shm_buf->rt_status.storage_no[STORAGE_NO].humidityMAX = 100;
	shm_buf->rt_status.storage_no[STORAGE_NO].illumination = house_env->ill;
	shm_buf->rt_status.storage_no[STORAGE_NO].illuminationMIN = 0;
	shm_buf->rt_status.storage_no[STORAGE_NO].illuminationMAX = 10000;
	shm_buf->rt_status.storage_no[STORAGE_NO].battery = house_env->bat;
	shm_buf->rt_status.storage_no[STORAGE_NO].adc = house_env->adc;

	sem_v(p_ipc_info->semid, 0);

	if (shmdt(shm_buf) == -1)
	{
		perror("shmdt");
		return;
	}
}
